package com.cavy.platform.server.domain;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.domain.job.BuildJob;
import com.cavy.platform.server.domain.job.Job;
import com.cavy.platform.server.domain.job.PendingJob;
import com.cavy.platform.server.repository.PipelineRepository;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 唐旭
 * @Date 2018/7/18
 */
@Data
@Accessors(chain = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "className", defaultImpl = Pipeline.class)
@JsonSubTypes({
        @JsonSubTypes.Type(value = GitRemotePipeline.class, name = "GitRemotePipeline"),
        @JsonSubTypes.Type(value = Pipeline.class, name = "Pipeline"),
        @JsonSubTypes.Type(value = SvnRemotePipeline.class, name = "SvnRemotePipeline")})
public class Pipeline implements BuildJob {
    //构建名称
    protected String name;
    //项目
    protected Project project;
    //构建步骤
    protected List<Stage> stageList = new ArrayList<>();
    //调度策略
    protected SchedulingStrategy schedulingStrategy = SchedulingStrategy.RANDOM;

    @JsonIgnore
    private transient PipelineRepository repository = BeansProvider.getBean(PipelineRepository.class);

    public Pipeline() {
    }

    public Pipeline(String name, String projectName, String workspace) {
        this.name = name;
        this.project = new Project().setName(projectName).setWorkSpace(new WorkSpace().setName(workspace));
    }

    public void addStage(Stage stage) {
        stageList.add(stage);
        repository.save(this);
    }

    public void removeStage(String name) {
        Iterator<Stage> iterator = this.getStageList().iterator();
        while (iterator.hasNext()) {
            Stage next = iterator.next();
            if (next.getName().equals(name)) {
                iterator.remove();
            }
        }
        repository.save(this);
    }

    public Stage findStage(String stageName) {
        Iterator<Stage> iterator = this.getStageList().iterator();
        while (iterator.hasNext()) {
            Stage next = iterator.next();
            if (next.getName().equals(stageName)) {
                return next;
            }
        }
        throw new RuntimeException("未找名称为:" + stageName + "的步骤");
    }

    @Override
    public PendingJob jobBuild(JobConfig jobConfig) {
        Job build = getJobInstance().setPipelineName(name).setProjectName(project.getName()).setWorkspaceName(project.getWorkSpace().getName()).setSchedulingStrategy(schedulingStrategy);
        build.addAllStage(this.stageList);
        return new PendingJob(build, jobConfig);
    }

    protected Job getJobInstance() {
        return new Job();
    }
}
